//
//  DetailViewController.m
//  shise
//
//  Created by 徐国庆 on 14/12/23.
//  Copyright (c) 2014年 MZP. All rights reserved.
//

#import "DetailViewController.h"
#import "NetHandler.h"
#import "Food.h"
#import "MoreDetailCell.h"
#import "UIImageView+WebCache.h"
#import "CrossSlipDetailOneCell.h"
#import "MoreDetailCell.h"
#import "ActivityDetailAndDetailCell.h"
#import "DetailPraiseAndLookCell.h"
#import "MenuCell.h"
#import "CrossSlipCell.h"
#import "Scroll.h"
#import "CrossSlipDetailViewController.h"
#import "UserDetailViewController.h"
#import "SJAvatarBrowser.h"
#import "ViewController.h"
#import "AppDelegate.h"
#import "WeiboSDK.h"
//#import <ShareSDK/ShareSDK.h>


@interface DetailViewController ()<UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, retain)UITableView *tableView;
// 定义可变数组装解析数据之后整理成Food类型的对象
@property(nonatomic, retain)NSMutableArray *array;
// 定义可变数组装解析数据之后整理成Scroll类型的对象
@property(nonatomic, retain)NSMutableArray *arrayOfMenu;
@property(nonatomic, assign)NSInteger numberOfCell;

//@property (nonatomic, retain) Food *food;

@end

@implementation DetailViewController

- (void)dealloc
{
    [_array release];
    [_tableView release];
    [_arrayOfMenu release];
    [_detailApi release];
    
    [super dealloc];
}

// 初始化数组
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.array = [NSMutableArray array];
        self.arrayOfMenu = [NSMutableArray array];
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor redColor];
    
    // tableView的坐标大小和view的坐标大小一样
//    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button setTitle:@"分享" forState:UIControlStateNormal];
    
    [button setFrame:CGRectMake(self.view.frame.size.width - 50, 0, 40, 40)];
    [self.view addSubview:button];
    [button addTarget:self action:@selector(login:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem =  [[UIBarButtonItem alloc] initWithCustomView:button];

    
    [self handleData];
    
    self.title = @"详情";

}


- (void)login:(UIButton *)bar
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    if ([user objectForKey:@"userName"] == nil) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登陆" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
        [alert release];
    } else {
    
    AppDelegate *myDelegate =(AppDelegate*)[[UIApplication sharedApplication] delegate];
    
    WBAuthorizeRequest *authRequest = [WBAuthorizeRequest request];
    authRequest.redirectURI = @"https://www.sina.com";
    authRequest.scope = @"all";
    
    WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:[self messageToShare] authInfo:authRequest access_token:myDelegate.wbtoken];
    request.userInfo = @{@"ShareMessageFrom": @"SendMessageToWeiboViewController",
                         @"Other_Info_1": [NSNumber numberWithInt:123],
                         @"Other_Info_2": @[@"obj1", @"obj2"],
                         @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
    //    request.shouldOpenWeiboAppInstallPageIfNotInstalled = NO;
    [WeiboSDK sendRequest:request];
    }
}

- (WBMessageObject *)messageToShare
{
    //分享本地的图片文字
//    WBMessageObject *message = [WBMessageObject message];
//    NSString *str = @"IntimateGift真的是一款很好很赞的软件哦！";
//    message.text = str;
//    WBImageObject *image = [WBImageObject object];
//    image.imageData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"1" ofType:@"jpg"]];
//    message.imageObject = image;
//    return message;
    
    Food *food = [self.array objectAtIndex:0];
    
    WBMessageObject *message = [WBMessageObject message];
    NSString *str = @"如果你是一枚资深的吃货，如果你也热爱生活，热爱美食，那就跟我一起下载餓吧，一款吃货必备的软件:  餓（e)  ，可前往AppStore，搜索餓，就可以下载啦。";
    message.text = str;
    WBImageObject *image = [WBImageObject object];
    NSString *path = food.pic_url;
    NSURL *url = [NSURL URLWithString:path];
    image.imageData = [NSData dataWithContentsOfURL:url];
    message.imageObject = image;
    return message;
    
}
// 设置cell的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.array.count;
}

// 设置cell的数据
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    Food *food = [self.array objectAtIndex:indexPath.row];
    
    if ([food.type isEqualToString:@"ImageCard"]) {
        
        NSString *string = @"ss";
        CrossSlipDetailOneCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
        if (cell == nil) {
            
            cell = [[[CrossSlipDetailOneCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string]autorelease];
        }
        
          [cell.userHeadImageViewButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        //[cell.activityImageView addSubview:button];
        cell.userHeadImageViewButton.tag = 102;
        
        
        [cell.activityImageView setImageWithURL:[NSURL URLWithString:food.pic_url]];
        
        
        
        return cell;
    } else if([food.type isEqualToString:@"UserCard"]){
        
        NSString *string = @"ad";
        ActivityDetailAndDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
        if (cell == nil) {
            
            cell = [[[ActivityDetailAndDetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string]autorelease];
            
        }
        NSDictionary *dic = food.user;
        NSString *str = [dic objectForKey:@"avatar"];
        [cell.userHeadImageView setImageWithURL:[NSURL URLWithString:str]];
        
        int len = 0;
        for (int i = 0; i  < food.userName.length; i ++) {
            
            unichar ch= [food.userName characterAtIndex:i];
            if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
                
                len ++;
            }
        }
        cell.userNameLabel.frame = CGRectMake(43, 5, len * 8 + (food.userName.length - len) * 13, 20);
        cell.userNameLabel.text = food.userName;
        cell.levelImageView.frame = CGRectMake(40 + food.userName.length * 13, 10, 30, 20);
//        cell.levelImageView.image = [UIImage imageNamed:@"mark.png"];
        cell.levelLabel.text = food.date;
        cell.timeLabel.text = food.desc;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell;
        
    } else if([food.type isEqualToString:@"ContentCard"]){
        
        NSString *string = @"dd";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
        if (cell == nil) {
            
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string]autorelease];
        }
        cell.textLabel.font = [UIFont systemFontOfSize:13];
        cell.textLabel.numberOfLines = 0;
        cell.textLabel.alpha = 0.5;
        
        cell.textLabel.text = food.content;
        return cell;
    } else if([food.type isEqualToString:@"LikeCard"]){
        
        self.numberOfCell = indexPath.row;
        
        NSString *string = @"cs";
        DetailPraiseAndLookCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
        if (cell == nil) {
            
            cell = [[[DetailPraiseAndLookCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string]autorelease];
        }
        NSMutableArray *arr = [NSMutableArray array];
        NSString *str = [NSString stringWithFormat:@"https://api.shiseapp.com%@", food.moreApi];
//        NSLog(@"大大的详情%@", str);
        [NetHandler getDataWithUrl:str completion:^(NSData *data) {
            
            NSError *error = nil;
            NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
            [arr addObjectsFromArray:[dictionary objectForKey:@"data"]];
            NSInteger number = arr.count;
            NSString *s = [NSString stringWithFormat:@"%ld", (long)number];
            NSString *pariseCount = [food.userName stringByReplacingOccurrencesOfString:@"%d" withString:s];
            cell.praiseAndLookLabel.text = pariseCount;
//            UIImageView *imageViewOne = [[UIImageView alloc] initWithFrame:CGRectMake(13, 0, 30, 30)];
//            //                imageViewOne.backgroundColor = [UIColor redColor];
//            [cell.praiseScrollView addSubview:imageViewOne];
//            imageViewOne.image = [UIImage imageNamed:@"praiseFont.png"];
            for (int i = 0; i < arr.count; i ++) {
                
                NSDictionary *tempDic = [arr objectAtIndex:i];
                
                NSDictionary *temp = [tempDic objectForKey:@"user"];
                NSString *tempString = [temp objectForKey:@"avatar"];
                //                self.userHeadImageView.layer.masksToBounds = YES;
                //                self.userHeadImageView.layer.cornerRadius = 16;
//                UIImageView *imageViewOne = [[UIImageView alloc] initWithFrame:CGRectMake(13, 0, 30, 30)];
//                //                imageViewOne.backgroundColor = [UIColor redColor];
//                [cell.praiseScrollView addSubview:imageViewOne];
//                imageViewOne.image = [UIImage imageNamed:@"praiseFont.png"];
                UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20 + i * 39, 0, 30, 30)];
                imageView.layer.masksToBounds = YES;
                imageView.layer.cornerRadius = 15;
                                NSLog(@"图片的地址%@", tempString);
                [imageView setImageWithURL:[NSURL URLWithString:tempString]];
                [cell.praiseScrollView addSubview:imageView];
                UIButton *imageViewButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
                imageViewButton.frame = imageView.frame;
                imageViewButton.layer.masksToBounds = YES;
                imageViewButton.layer.cornerRadius = 15;
                imageViewButton.tag = 1000 + i;
                [cell.praiseScrollView addSubview:imageViewButton];
//                NSString *imageViewString = [temp objectForKey:@"id"];
                [imageViewButton addTarget:self action:@selector(imageViewButtonAction:) forControlEvents:UIControlEventTouchUpInside];
                [imageView release];
                
            }
        }];
        return cell;
    } else if ([food.type isEqualToString:@"TitleCard"]) {
        
        NSString *string = @"sss";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
        if (cell == nil) {
            
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string]autorelease];
            
        }
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        cell.textLabel.alpha = 0.7;
        
        NSString *str = [NSString stringWithFormat:@"%@--下厨房", food.userName];
        // 设置cell右边的箭头
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = str;
        return cell;
    } else if ([food.type isEqualToString:@"SeparatorCard"] && [food.center isEqualToString:@"1"]) {
        
        NSString *string = @"dad";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
        if (cell == nil) {
            
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string]autorelease];
            
        }
        
        if ([food.userName hasPrefix:@"查看全部"]) {
            
            
        } else {
            
            cell.textLabel.text = food.userName;
            cell.textLabel.textAlignment = NSTextAlignmentCenter;
            cell.textLabel.font = [UIFont systemFontOfSize:13];
            cell.textLabel.alpha = 0.5;
            
        }
        
        return cell;
    } else if ([food.type isEqualToString:@"TwoCard"]) {
        
        
        NSString *string = @"fsf";
        MenuCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
        if (cell == nil) {
            
            cell = [[[MenuCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string]autorelease];
        }
        
        cell.textLabel.alpha = 0.5;
        [cell.menuOne setImageWithURL:[NSURL URLWithString:food.menuOne]];
        [cell.menuTwo setImageWithURL:[NSURL URLWithString:food.menuTwo]];
        // 为按钮设置tag值 当点击cell的时候通过tag取出数组中的数据
        cell.menuOneButton.tag = 2000 + indexPath.row;
        [cell.menuOneButton addTarget:self action:@selector(menuButtonOneAction:) forControlEvents:UIControlEventTouchUpInside];
        cell.menuTwoButton.tag = 3000 + indexPath.row;
        [cell.menuTwoButton addTarget:self action:@selector(menuButtonTwoAction:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
        
    } else if ([food.type isEqualToString:@"TopicCard"]) {
        
        NSString *string = @"uyty";
        CrossSlipCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
        if (cell == nil) {
            
            cell = [[[CrossSlipCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string]autorelease];
            
        }
        Scroll *scroll = [self.arrayOfMenu objectAtIndex:indexPath.row];
        cell.activityImageView.image = [UIImage imageNamed:@"activity.png"];
        cell.numberOfPhotosAndEndDate.text = scroll.desc;
        cell.activityNameLabel.text = scroll.title;
        [cell.crossSlipButton addTarget:self action:@selector(crossSlipButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        cell.crossSlipButton.tag = 5000 + indexPath.row;
        for (int i = 0; i < scroll.pics.count; i ++) {
            
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * 155, 5, 150, 150)];
            NSDictionary *dic = [scroll.pics objectAtIndex:i];
            NSString *ss = [dic objectForKey:@"url"];
            [imageView setImageWithURL:[NSURL URLWithString:ss]];
            [cell.scrollView addSubview:imageView];
            [imageView release];
            
        }
        return cell;
        
    } else {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ada"];
        if (cell == nil) {
            
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ada"]autorelease];
            
        }
        return cell;
        
    }
}


//放大图片的方法
- (void)buttonAction:(UIButton *)button
{
    UIButton *butt = (UIButton *)[self.view viewWithTag:102];

    [SJAvatarBrowser showImage:(UIImageView *)[butt superview]];
}


// 自定义处理数据的方法
- (void)handleData
{
//    NSString *address = [NSString stringWithFormat:@"https://api.shiseapp.com%@", self.detailApi];
    NSString *address = [NSString stringWithFormat:@"https://api.shiseapp.com%@&_version=2.5.0&conf_ver=1420018423&gps=38.883330,121.540111&uuid=44cd1914a02fab9e63fb7ec1fbf910e0", self.detailApi];

    NSLog(@"详情的详情的地址%@", address);
    [NetHandler getDataWithUrl:address completion:^(NSData *data) {
        
        NSError *error = nil;
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        
        NSArray *arr = [dic objectForKey:@"data"];
        
        for (NSDictionary *tempDic in arr) {
            
            Food *food = [[Food alloc] initWithDictionary:tempDic];
            Scroll *scroll = [[Scroll alloc] initWithDictionary:tempDic];
            [self.array addObject:food];
            [self.arrayOfMenu addObject:scroll];
            [food release];
            [scroll release];
        }
        
        [self.tableView reloadData];
    }];
}



// 设置cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    if (self.array.count >= 12) {
    Food *food = [self.array objectAtIndex:indexPath.row];
        if ([food.type isEqualToString:@"ImageCard"]) {
            
            return self.view.frame.size.width;
        } else if ([food.type isEqualToString:@"UserCard"]) {
            
            return 50;
        }  else if ([food.type isEqualToString:@"ContentCard"]) {
            
            Food *food = [self.array objectAtIndex:indexPath.row];
            NSString *string = food.content;
            NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:13]};
            
            CGRect rect = [string boundingRectWithSize:CGSizeMake(tableView.frame.size.width, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
            if (rect.size.height == 0) {
                
                return 0;
            }
            return rect.size.height + 20;
        } else if ([food.type isEqualToString:@"LikeCard"]) {
            
            return 65;
        } else if ([food.type isEqualToString:@"TitleCard"]) {
            
            return 35;
        } else if ([food.type isEqualToString:@"SeparatorCard"] && [food.center isEqualToString:@"1"] && ![food.userName hasPrefix:@"查看全部"]) {
            
            return 20;
        } else if ([food.type isEqualToString:@"TwoCard"]){
            
            return 170;
        } else if ([food.type isEqualToString:@"TopicCard"]) {
            
            return 210;
        }else {
            
            return 0;
        }
}


// 点击横向滑动按钮事件
- (void)crossSlipButtonAction:(UIButton *)button
{
    
    Scroll *scroll = [self.arrayOfMenu objectAtIndex:button.tag - 5000];
    Food *food = [self.array objectAtIndex:button.tag - 5000];
    if (food.url.length == 0) {
        
        CrossSlipDetailViewController *crossSlipDetailVC = [[CrossSlipDetailViewController alloc] init];
        crossSlipDetailVC.address = scroll.api;
        NSLog(@"%@", crossSlipDetailVC.address);
        [self.navigationController pushViewController:crossSlipDetailVC animated:YES];
        [crossSlipDetailVC release];
    } else {
        
        ViewController *VC = [[ViewController alloc] init];
        VC.str = food.url;
        [self.navigationController pushViewController:VC animated:YES];
        [VC release];
    }
    
}

// 点击相关菜谱按钮执行的方法
- (void) menuButtonOneAction:(UIButton *)button
{
    Food *food = [self.array objectAtIndex:button.tag - 2000];
    ViewController *VC = [[ViewController alloc] init];
    VC.str = food.webViewUrlOne;
    [self.navigationController pushViewController:VC animated:YES];
    [VC release];
    
}

// 点击“相关菜谱下面的图片的方法”
- (void) menuButtonTwoAction:(UIButton *)button
{
    
    Food *food = [self.array objectAtIndex:button.tag - 3000];
    ViewController *VC = [[ViewController alloc] init];
    VC.str = food.webViewUrlTwo;
    [self.navigationController pushViewController:VC animated:YES];
    [VC release];
    
}

// 点击赞的人的头像执行的方法
- (void)imageViewButtonAction:(UIButton *)button
{
    Food *food = [self.array objectAtIndex:self.numberOfCell];
    
    NSMutableArray *arr = [NSMutableArray array];
    NSString *str = [NSString stringWithFormat:@"https://api.shiseapp.com%@", food.moreApi];
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        
        NSError *error = nil;
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        [arr addObjectsFromArray:[dictionary objectForKey:@"data"]];
        for (int i = 0; i < arr.count; i ++) {
            
            NSDictionary *tempDic = [arr objectAtIndex:i];
            
            NSDictionary *temp = [tempDic objectForKey:@"user"];
            NSString *imageViewString = [temp objectForKey:@"id"];
            if (i == button.tag - 1000) {
                
                UserDetailViewController *userDetaileVC = [[UserDetailViewController alloc]init];
                userDetaileVC.userApi = imageViewString;
                [self.navigationController pushViewController:userDetaileVC animated:YES];
                [userDetaileVC release];
            }
        }
    }];
    
}
// 点击cell执行的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    //让cell点击以后回弹
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    Food *food = [self.array objectAtIndex:indexPath.row];
    if ([food.type isEqualToString:@"TitleCard"]) {
        
        Food *food = [self.array objectAtIndex:indexPath.row];
        ViewController *VC = [[ViewController alloc] init];
        // userName是下厨房前面的字符串   使用webView需要对字符串进行截取 取出关键字 将关键字作为地址参数进行传输
        // 开始截取字符串  字符串的原形式是“查看"红糖美味面包🍞"相关菜谱”的 要把其中的“红糖美味面包🍞”取出来
        NSRange rang = NSMakeRange(3, food.userName.length - 8);
        NSString *subString = [food.userName substringWithRange:rang];
        NSString *webViewUrl = [NSString stringWithFormat:@"http://mpartner.xiachufang.com/search/?ref=shise&keyword=%@", subString];
        VC.str = webViewUrl;
        [self.navigationController pushViewController:VC animated:YES];
        [VC release];

        
    } else if ([food.type isEqualToString:@"UserCard"]) {
        
        NSDictionary *dic = food.user;
        UserDetailViewController *userDetaileVC = [[UserDetailViewController alloc]init];
        userDetaileVC.userApi = [dic objectForKey:@"id"];
        [self.navigationController pushViewController:userDetaileVC animated:YES];
        [userDetaileVC release];
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
